#include "PAC9685_Driver.h"

#pragma region //=============字段================
sI2C_DRIVER *pPWM_Drv;
#pragma endregion

#pragma region //===============方法=================
void PAC9685_Init(void *handle, osSemaphoreId DoneSemId)
{
	I2C_Init(&pPWM_Drv, (I2C_HandleTypeDef*)handle, DoneSemId);
	
	//复位器件
	HAL_GPIO_WritePin(nPWM_OE_GPIO_Port, nPWM_OE_Pin, GPIO_PIN_SET);
	uint8_t addr = SWRST_ADDR, cmd = SWRST_CMD;
	I2C_WriteCommand(pPWM_Drv, addr, cmd);
	
	//配置PWM频率=max1526Hz
	addr = (uint32_t)&PAC9685_Reg->PRE_SCALE;
	uint8_t data[2] = { 0x03, 0 };
	I2C_WriteRegister(pPWM_Drv, PAC9685_ADDR, addr, data, 1);
	
	//配置MODE1,2
	addr = (uint32_t)&PAC9685_Reg->MODE[0];
	data[0] = AI;
	data[1] = OCH | OUTDRV;	//在所有4个PWM通道寄存器加载最后一个ACK上的输出改变。16个PWM输出配置为图腾柱结构。
	I2C_WriteRegister(pPWM_Drv, PAC9685_ADDR, addr, data, 2);
	osDelay(2);
	HAL_GPIO_WritePin(nPWM_OE_GPIO_Port, nPWM_OE_Pin, GPIO_PIN_RESET); //使能PWM输出
}
/*
********************************************************************************
 *描述: 向PAC9685的某个通道写入新的脉宽数据
 ******************************************************************************/
void PAC_WrPWM(uint8_t channel/*[I]0~15通道之一*/, uint16_t pwm/*[I]新的脉宽数据0~4095*/)
{
	uint16_t data[2];
	if (pwm >= 4095)//常开
	{
		data[0] = 4096;	//ON[12]=1
		data[1] = 0;
	}
	else if (pwm == 0)//常闭
	{
		data[0] = 0;
		data[1] = 4096;	//OFF[12]=1
	}
	else//pwm输出
	{
		data[0] = 0;
		data[1] = pwm;
	}
	I2C_WriteRegister(pPWM_Drv, PAC9685_ADDR, channel * 4 + 6, (uint8_t*)data, 4);
}
#pragma endregion


